package dao;

import com.alibaba.fastjson.JSON;
import domin.BookCategory;
import lombok.extern.slf4j.Slf4j;

import util.CommonDao;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.TreeSet;

@Slf4j
public class BookCategoryDao {
    private static BookCategoryDao bookCategoryDao = new BookCategoryDao();
    private BookCategoryDao(){}
    public static BookCategoryDao getInstance(){
        return bookCategoryDao;
    }
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;
    public BookCategory find (Connection connection , int id) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM bookcategory where id=?");
        preparedStatement.setInt(1,id);
        ResultSet resultSet = preparedStatement.executeQuery();
        BookCategory bookCategory = null;
        if (resultSet.next()){
            bookCategory = new BookCategory();
            bookCategory.setId(resultSet.getInt("id")); ;
            bookCategory.setCategory(resultSet.getString("category")) ;
            bookCategory.setNo(resultSet.getString("no")); ;
        }
        JdbcHelper.close(resultSet,preparedStatement);
        return bookCategory;
    }
    public Collection<BookCategory> findAll(Connection connection, Collection<Condition> condition, Pagination pagination) throws SQLException {
        Collection<BookCategory> books = new TreeSet<BookCategory>();
        int totalNum = CommonDao.getInstance().count(connection,"bookcategory");
        String sql_select_all = "SELECT * FROM bookcategory ";
        if (condition != null){
            sql_select_all += Condition.toWhereClause(JSON.toJSONString(condition));
            log.trace(sql_select_all);
        }
        if (pagination != null){
            sql_select_all += pagination.toLimitClause(totalNum);
            log.trace(sql_select_all);
        }
        this.preparedStatement = connection.prepareStatement(sql_select_all);
        this.resultSet = preparedStatement.executeQuery();
        while (this.resultSet.next()){
            BookCategory bookCategory = new BookCategory();
            bookCategory = new BookCategory();
            bookCategory.setId(resultSet.getInt("id")); ;
            bookCategory.setCategory(resultSet.getString("category")) ;
            bookCategory.setNo(resultSet.getString("no")); ;
            books.add(bookCategory);
        }
        JdbcHelper.close(this.resultSet,this.preparedStatement);
        return books;
    }
}
